import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import _ from 'lodash';
import qs from 'qs';

import { addTab } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Button,
  Card,
  Row,
  Col,
  Input,
  Table,
  Radio,
  Menu,
  Dropdown,
  Divider,
  Tooltip,
  Popconfirm,
} from 'antd';
import { DownOutlined } from '@ant-design/icons';

import '@ant-design/compatible/assets/index.css';
import SaveLogisticsElem from './components/SaveLogisticsElem';

const { pathname } = window.location;

const prompt: any = {
  textAlign: 'center',
  marginBottom: 0,
  background: 'rgba(248,231,28,0.16)',
  color: 'rgb(202, 120, 120)',
  fontSize: 12,
};

interface ExpressInfoProps extends FormComponentProps {
  dispatch: Dispatch;
  expressInfo: any;
  workMode: any;
  checkPerm: any;
  location: { query: any };
  screen: string;
  loading: boolean;
}

interface ExpressInfoState {
  searchValues: any;
  pageIndex: number;
  pageSize: number;
  visible: boolean;
  workMode: string[];
  rowId: number;
}

@connect(({
  expressInfoList: { expressInfo, workMode },
  common: { checkPerm },
  global: { screen },
  loading,
}: any) => ({
  expressInfo,
  workMode,
  checkPerm,
  screen,
  loading: loading.effects['expressInfoList/fetchExpressList'],
}))
class ExpressInfoElem extends Component<ExpressInfoProps, ExpressInfoState> {
  columns = [
    {
      title: '快递公司',
      dataIndex: 'expressName',
      width: 120,
      render: (text: string) => (
        <Tooltip title={text || '--'}>
          <div className="wordOmit">{text || '--'}</div>
        </Tooltip>
      ),
    },
    {
      title: '固定电话',
      dataIndex: 'expressPhone',
      width: 120,
      render: (text: string) => (
        <Tooltip title={text || '--'}>
          <div className="wordOmit">{text || '--'}</div>
        </Tooltip>
      ),
    },
    {
      title: '当前设置作业方式',
      dataIndex: 'setWorkModeName',
      width: 160,
    },
    {
      title: '已生效作业方式',
      dataIndex: 'workModeName',
      width: 160,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 180,
    },
    {
      title: '操作',
      dataIndex: 'id',
      width: 160,
      render: (id: number, record: any) => {
        const { checkPerm } = this.props;
        return (
          <>
            {checkPerm.operOther && (
              <span>
                <Dropdown arrow overlay={() => this.menuGroup(record)} trigger={['click']}>
                  <span className="operLink">
                    设置作业方式 <DownOutlined />
                  </span>
                </Dropdown>
                <Divider type="vertical" />
              </span>
            )}
            {checkPerm.update && (
              <Popconfirm
                title="确定删除当前快递公司吗？"
                onConfirm={() => this.handleDelete(id)}
                className="operLink"
                okText="确定"
                cancelText="取消"
              >
                删除
              </Popconfirm>
            )}
          </>
        );
      },
    },
  ];

  state: ExpressInfoState = {
    searchValues: {},
    pageIndex: 1,
    pageSize: 20,
    visible: false,
    workMode: [],
    rowId: 0,
  };

  static getDerivedStateFromProps(nextProps: ExpressInfoProps) {
    const { workMode, location: { query } } = nextProps;
    const { pageIndex, pageSize, ...searchValues } = query;
    const new_workMode = [...Object.values(workMode)];

    return {
      workMode: new_workMode,
      searchValues,
      pageIndex: Number(pageIndex) || 1,
      pageSize: Number(pageSize) || (nextProps.screen === 'sm' ? 100 : 20),
    };
  }

  componentDidMount() {
    this.setFieldsValue();

    const { expressInfo } = this.props;
    if (expressInfo?.list?.length) return;

    this.fetchDataValues();
    this.verifyPermissions();
    this.fetchAction('fetchWorkMode');
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { searchValues, pageIndex, pageSize }: any = this.state;
    if (!_.isEqual(searchValues, prevState.searchValues)
      || pageIndex !== prevState.pageIndex
      || pageSize !== prevState.pageSize
      || searchValues.id !== prevState.searchValues.id
    ) {
      this.setFieldsValue();
      this.fetchDataValues();
    }
  }

  // 设置表单
  setFieldsValue = () => {
    const { searchValues: { name } } = this.state;
    const { form: { setFieldsValue } } = this.props;
    setFieldsValue({ name });
  };

  fetchDataValues = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'expressInfoList/fetchExpressList',
      payload: this.getQueryParams(),
    });
  };

  getQueryParams = () => {
    const { searchValues, pageIndex, pageSize } = this.state;
    const params = {
      ...searchValues,
      pageIndex,
      pageSize,
    };
    return params;
  };

  verifyPermissions = () => {
    const addparams = {
      name: 'add',
      oper: 'add',
      resource: 'conf:delpoy_express',
    };
    this.fetchAction('common/fetchCheckPerm', addparams);

    const updateparams = {
      name: 'update',
      oper: 'delete',
      resource: 'conf:delpoy_express',
    };
    this.fetchAction('common/fetchCheckPerm', updateparams);

    const otherparams = {
      name: 'operOther',
      oper: 'list',
      resource: 'conf:delpoy_express',
    };
    this.fetchAction('common/fetchCheckPerm', otherparams);
  };

  menuGroup = (record: any) => {
    const { workMode } = this.state;

    return (
      <Menu className="radioGroup">
        {workMode.map((item: string, index: number) => (
          <Menu.Item key={item}>
            <Radio
              checked={record.setWorkMode === index && true}
              disabled={record.setWorkMode === index && true}
              value={index}
              onChange={e => this.handleChangeType(record, e)}
            >
              {item}
            </Radio>
          </Menu.Item>
        ))}
        <p style={prompt}>注：修改配置后，次日生效。</p>
      </Menu>
    );
  };

  handleChangeType = ({ id }: any, e: any) => {
    const { searchValues: search } = this.state;
    const params = {
      search,
      id,
      value: e.target.value,
    };
    this.fetchAction('updateType', params);
  };

  handleDelete = (id: number) => {
    const { searchValues: search } = this.state;
    const params = { id, search };
    this.fetchAction('deleteExpress', params);
  };

  handleChangeModal = (visible: boolean) => {
    if (visible) {
      this.fetchAction('fetchLogistics');
    }
    this.setState({ visible });
  };

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFields } } = this.props;
    validateFields((errors, values) => {
      if (errors) return;

      const { searchValues } = this.state;
      const query = {
        ...searchValues,
        ...values,
        pageIndex: 1,
        pageSize: 20,
      };

      const { dispatch } = this.props;
      addTab(dispatch, {
        name: `公司${searchValues.logisName}`,
        url: `${pathname}?${qs.stringify(query)}`,
        isTopMenu: true,
      });
    });
  };

  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { searchValues: { id, logisName } } = this.state;
    const query = { id, logisName };
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `公司${logisName}`,
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  };

  onSelectChange = (pageIndex: number, pageSize: number) => {
    const { searchValues } = this.state;
    const query = {
      ...searchValues,
      pageIndex,
      pageSize,
    };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `公司${searchValues.logisName}`,
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  };

  fetchAction = (typeName: string, payload = {}) => {
    const type = typeName.indexOf('common') >= 0
      ? typeName : `expressInfoList/${typeName}`;

    const { dispatch } = this.props;
    dispatch({ type, payload });
  };

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  render() {
    const {
      searchValues,
      pageIndex,
      pageSize,
      visible,
    } = this.state;

    const {
      form: { getFieldDecorator },
      expressInfo,
      checkPerm,
      location: { query },
      loading,
    } = this.props;

    const dataSource = expressInfo.list || [];
    const pagination: object = {
      total: expressInfo.count,
      current: pageIndex,
      pageSize,
      showQuickJumper: true,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '50', '100'],
      onChange: this.onSelectChange,
      onShowSizeChange: this.onSelectChange,
    };

    const { logisName }: any = searchValues;

    return (
      <Fragment>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          <Form className="tableListForm" onSubmit={this.handleSearch}>
            <Row gutter={12}>
              <Col md={6} sm={24}>
                <Form.Item label="物流中心">
                  <div>{logisName}</div>
                </Form.Item>
              </Col>
              <Col md={6} sm={24}>
                <Form.Item label="快递公司" colon={false}>
                  {getFieldDecorator('name')(
                    <Input allowClear placeholder="请输入" />,
                  )}
                </Form.Item>
              </Col>
              <Col md={12} sm={24}>
                <div className="flexFeView">
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="smallButton"
                  >
                    查询
                  </Button>
                  <Button
                    type="primary"
                    className="addButton smallButton marginL16"
                    onClick={this.handleReset}
                  >
                    重置
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card className="tableList" bordered={false}>
          {
            checkPerm.add && (
              <div className="tableBtns">
                <Button
                  type="primary"
                  size="small"
                  className="smallButton"
                  onClick={() => this.handleChangeModal(true)}
                >
                  添加快递公司
                </Button>
              </div>
            )
          }
          <Table
            rowKey="id"
            tableLayout="fixed"
            className="statementTable tableHeight60"
            columns={this.columns}
            dataSource={dataSource}
            pagination={pagination}
            loading={loading}
            scroll={{ x: 980 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>

        <SaveLogisticsElem
          visible={visible}
          state={query}
          expressValues={{ ...searchValues, pageIndex, pageSize }}
          changeModal={this.handleChangeModal.bind(this)}
        />
      </Fragment>
    );
  }
}

export default Form.create<ExpressInfoProps>()(ExpressInfoElem);
